<?php

namespace app\web\service;
use app\web\model\Order;
use app\web\model\Goods;
use app\web\model\OrderSub;
use app\web\util\AlibabaUtil;
use think\Facade\Db;

class PrintService
{
    /**
     * @return list
     * @todo 分页查询数据
     * @aothor YangFan
     */
    public static function page(int $page, int $pageSize, $where,$whereBetweentTime,$is_all)
    {
        $order_model = new Order();
        if($is_all==1){
            $list = $order_model->alias('o')
            ->field('o.id as oid,o.pay_time,o.modify_time,to_full_name,o.to_division_code,o.to_mobile,o.transaction_id,
                     o.buyer_feedback,o.seller_memo,o.total_amount,o.sign,o.invoice_content,o.express_print_state,
                     o.invoice_print_state,o.buyer_login_id,o.status,o.shipping_fee,o.to_phone')
            ->where($where)
            ->whereBetweenTime('pay_time|modify_time',$whereBetweentTime[1],$whereBetweentTime[2])
            ->order($whereBetweentTime[0], 'desc')
            ->paginate([
                'page' => $page,
                'list_rows' => $pageSize,
            ]);
        }else{
            $list = $order_model->alias('o')
            ->field('o.id as oid,o.pay_time,o.modify_time,to_full_name,o.to_division_code,o.to_mobile,o.transaction_id,
                     o.buyer_feedback,o.seller_memo,o.total_amount,o.sign,o.invoice_content,o.express_print_state,
                     o.invoice_print_state,o.buyer_login_id,o.status,o.refund_status,o.shipping_fee,o.to_phone')
            ->where($where)
            ->whereBetweenTime($whereBetweentTime[0],$whereBetweentTime[1],$whereBetweentTime[2])
            ->order($whereBetweentTime[0], 'desc')
            ->paginate([
                'page' => $page,
                'list_rows' => $pageSize,
            ]);
        }
        return $list;
    }
    public static function order_area($transaction_id){
        $order_model = new Order();
        $list = $order_model->alias('o')
            ->field('o.u_area as area,o.u_city as city,o.u_province as province,o.u_town as town,o.u_address as address,
            CONCAT_WS(" ",u_province,u_city,u_area,u_town,u_address) as to_area')
            ->where('transaction_id',$transaction_id)
            ->select()
            ->toArray();
            if($list[0]['area']!=null){
                return $list;
            }else{
                $list = $order_model->alias('o')
                ->field('o.area as area,o.city as city,o.province as province,o.town as town,o.address as address,o.to_area as to_area')
                ->where('transaction_id',$transaction_id)
                ->select()
                ->toArray();
                return $list;
            }
    }
    public static function order_sub($transaction_id){
        $ordersub_model = new OrderSub();
        $list = $ordersub_model->alias('o_s')
            ->leftjoin('goods g','o_s.product_id=g.product_id')
            ->leftjoin('goods_sku g_s','o_s.sku_id=g_s.sku_id')
            ->field('o_s.id as os_id,o_s.price,o_s.quantity,o_s.item_amount,o_s.name,o_s.product_img_url,
                     o_s.transaction_id,g.short_name as baby_short_name,g_s.short_name as sku_short_name,
                     o_s.sku_name,o_s.sku_value,o_s.skuinfos,o_s.statusStr')
            ->where('transaction_id',$transaction_id)
            ->select()
            ->toArray();
        return $list;
    }
    /**
     * @return list
     * @todo 查询自订单交易id
     * @aothor YangFan
     */
    public static function get_order_sub_transaction_id($name){
        $ordersub_model = new OrderSub();
        $list = $ordersub_model->alias('o_s')
            ->field('transaction_id')
            ->where('name','like','%'.$name.'%')
            ->select()
            ->toArray();
        return $list;
    }
    /**
     * @return result
     * @todo 查询买家数量
     * @aothor YangFan
     */
    public static function buyer_count($where,$whereBetweentTime,$is_all){
        if($is_all==1){
            $result = DB::table('order')->alias('o')
            ->where($where)
            ->whereBetweenTime('pay_time|modify_time',$whereBetweentTime[1],$whereBetweentTime[2])
            ->group('buyer_login_id')
            ->count();
        }else{
            $result = DB::table('order')->alias('o')
            ->where($where)
            ->whereBetweenTime($whereBetweentTime[0],$whereBetweentTime[1],$whereBetweentTime[2])
            ->group('buyer_login_id')
            ->count();
        }
        return $result;
    }
    /**
     * @return result
     * @todo 打印按条件查询信息
     * @aothor YangFan
     */
    public static function SearchOrderDetail($data,$shop_id)
    {
        $where[] =['o.shop_id','=',$shop_id];
        $whereBetweentTime = [];
        $now_time = date('Y-m-d H:i:s');
        $ali_util = new AlibabaUtil();
        //根据下单时间或者修改时间
        if(!empty($data['Time'])){
            $is_all=6;
            if($data['Time']==1){  //下单时间
                if(!empty($data['startTime']) && !empty($data['endTime'])){
                    $param['createStartTime'] = date("YmdHis",strtotime($data['startTime'])).'000+0800';
                    $param['createEndTime'] = date("YmdHis",strtotime($data['endTime'])).'000+0800';
                    $whereBetweentTime = ['pay_time',$data['startTime'],$data['endTime']];
                }else{
                    $param['createStartTime'] = $now_time;
                    $param['createEndTime'] = $now_time;
                    $whereBetweentTime =[];
                }
            }else if($data['Time']==2){  //修改时间
                if(!empty($data['startTime']) && !empty($data['endTime'])){
                    $param['modifyStartTime'] = date("YmdHis",strtotime($data['startTime'])).'000+0800';
                    $param['modifyEndTime'] = date("YmdHis",strtotime($data['endTime'])).'000+0800';
                    $whereBetweentTime = ['modify_time',$data['startTime'],$data['endTime']];
                }else{
                    $param['modifyStartTime'] = date("YmdHis",strtotime($now_time)).'000+0800';
                    $param['modifyEndTime'] = date("YmdHis",strtotime($now_time)).'000+0800';
                    $whereBetweentTime =[];
                }
            }else{
                //$param['createStartTime'] =date("Ymd",strtotime($now_time)).'000000000+0800';
                //$param['createEndTime'] =date("Ymd",strtotime($now_time)).'235959000+0800';
                //$param['modifyStartTime'] =date("Ymd",strtotime($now_time)).'000000000+0800';
                //$param['modifyEndTime'] =date("Ymd",strtotime($now_time)).'235959000+0800';
                //$whereBetweentTime = ['pay_time','0000-00-00 00:00:00','2099-01-01 00:00:00'];
                $is_all=1;
                $whereBetweentTime = ['pay_time',$data['startTime'],$data['endTime']];
            }
        }
        //根据订单类型查询
        if (!empty($data['trade_type'])) {
            if($data['trade_type']==88){  //全部
                $param['tradeType']='';
                $where[] =['trade_type','in','(1,2,3,4,5,6,7,8,9,10)'];
            }else{  //各种类型订单查询1:担保交易 2:预存款交易 3:ETC境外收单交易 4:即时到帐交易 5:保障金安全交易 6:统一交易流程 7:分阶段付款 8.货到付款交易 9.信用凭证支付交易 10.账期支付交易，50060 交易4.0
                $param['tradeType']=$data['trade_type'];
                $where[] =['trade_type','=',$data['trade_type']];
            }
        }
        //根据状态查询
        if(!empty($data['status'])){
            if($data['status']==1){  //等待买家付款
                $param['orderStatus']='waitbuyerpay';
                $where[] = ['o.status','=','waitbuyerpay'];
            }else if($data['status']==2){  //买家已付款
                $param['orderStatus']='waitsellersend';
                $where[] = ['o.status','=','waitsellersend'];
            }else if($data['status']==3){  //卖家已发货
                $param['orderStatus']='waitbuyerreceive';
                $where[] = ['o.status','=','waitbuyerreceive'];
            }else if($data['status']==4){  //交易成功
                $param['orderStatus']='success';
                $where[] = ['o.status','=','success'];
            }else{
                $param['orderStatus']='';
                $where[]='';
            }
        }
        //根据打印状态查询
        if(!empty($data['print_state'])){
            if($data['print_state']==1){   //仅快递单
                $where[] = ['o.express_print_state', '=', '1'];
                $where[] = ['o.invoice_print_state', '=', '0'];
            }else if($data['print_state']==2){  //仅发货单
                $where[] = ['o.express_print_state', '=', '0'];
                $where[] = ['o.invoice_print_state', '=', '1'];
            }else if($data['print_state']==3){  //均已打印
                $where[] = ['o.express_print_state', '=', '1'];
                $where[] = ['o.invoice_print_state', '=', '1'];
            }else if($data['print_state']==4){  //都未打印
                $where[] = ['o.express_print_state', '=', '0'];
                $where[] = ['o.invoice_print_state', '=', '0'];
            }else{
                $where[] = '';
            }
        }
        //根据退款状态查询
        if(!empty($data['refund_state'])){
            if($data['refund_state']==1){  //等待卖家同意
                $param['refundStatus']='waitselleragree';
                $where[] = ['o.refund_status','=','waitselleragree'];
            }else if($data['refund_state']==2){  //等待买家退货
                $param['refund_status']='waitbuyersend';
                $where[] = ['o.refund_status','=','waitbuyersend'];
            }else if($data['refund_state']==3){  //等待卖家确认收货
                $param['refundStatus']='waitsellerreceive';
                $where[] = ['o.refund_status','=','waitsellerreceive'];
            }else if($data['refund_state']==4){  //退款成功
                $param['refundStatus']='refundsuccess';
                $where[] = ['o.refund_status','=','refundsuccess'];
            }else{
                $param['refundStatus']='';
                $where[] ='';
            }
        }
        //根据旺旺/宝贝/
        if(!empty($data['ww_baby_count_money'])){
            if($data['ww_baby_count_money']==1){   //买家旺旺
                if(!empty($data['wangwang'])){
                    $where[] = ['o.buyer_login_id','in',$data['wangwang']];
                }else{
                    return array_response([],30000,"买家旺旺不能为空");
                }
                //$param['buyerMemberId'] =$data['wangwang'];
            }else if($data['ww_baby_count_money']==2){  //商品名称
                //$param['productName'] =$data['productName'];
                if(!empty($data['productName'])){
                    $transaction_id = self::get_order_sub_transaction_id($data['productName']);
                    foreach($transaction_id as $value){
                        $data[] = $value['transaction_id'];
                    }
                    $where[] = ['o.transaction_id','in',implode(',',$data)];
                }else{
                    return array_response([],30001,"商品名称不能为空");
                }
            }else{
                //$param['buyerMemberId']='';
                //$param['productName']='';
                $where[]='';
                $where_sub[]='';
            }
        }
        $param['needBuyerAddressAndPhone']='true';
        $param['needMemoInfo']='true';
        $param['needCheckSend']='true';
        $res = $ali_util->getSellerOrderList($shop_id,$param);
        if(array_key_exists('totalRecord',$res['data'])==true) {
            if ($res['data']['totalRecord'] > 0) {
                foreach ($res['data']['result'] as $value) {
                    $baseInfo = $value['baseInfo'];
                    $receiverInfo = $value['baseInfo']['receiverInfo'];
                    $nativeLogistics=$value['nativeLogistics'];
                    $data_order = array(
                        'shop_id' => $shop_id, //店铺ID
                        'transaction_id' => $baseInfo['id'],  //交易id
                        'all_delivered_time' => array_key_exists('allDeliveredTime', $baseInfo) == true ? date('Y-m-d H:i:s', strtotime(substr($baseInfo['allDeliveredTime'], 0, 14))) : "0000-00-00 00:00:00", //完全发货时间
                        'pay_time' => array_key_exists('payTime', $baseInfo) == true ? date("Y-m-d H:i:s", strtotime(substr($value['baseInfo']['payTime'], 0, 14))) : "0000-00-00 00:00:00", //付款时间，如果有多次付款，这里返回的是首次付款时间
                        'buyer_remark_icon' => array_key_exists('buyerRemarkIcon', $baseInfo) == true ? $baseInfo['buyerRemarkIcon'] : '', //买家备忘标志
                        'to_full_name' => $receiverInfo['toFullName'], //收件人
                        'to_division_code' => $receiverInfo['toDivisionCode'], //收货人地址区域编码
                        'to_mobile' => $receiverInfo['toMobile'], //收件人移动电话
                        'to_phone' => array_key_exists('toPhone', $receiverInfo) == true ? $receiverInfo['toPhone'] : '', //收件人电话
                        'to_post' => array_key_exists('toPost', $receiverInfo) == true ? $receiverInfo['toPost'] : '', //邮编
                        'to_town_code' => array_key_exists('toTownCode', $receiverInfo) == true ? $receiverInfo['toTownCode'] : '', //收货人街道或镇区域编码，可能为空
                        'to_area' => $receiverInfo['toArea'], //收货地址
                        'discount' => $baseInfo['discount'], //折扣信息，单位分
                        'refund_status' => array_key_exists('refundStatus', $baseInfo) == true ? $baseInfo['refundStatus'] : '', //订单的售中退款状态，等待卖家同意：waitselleragree ，待买家修改：waitbuyermodify，等待买家退货：waitbuyersend，等待卖家确认收货：waitsellerreceive，退款成功：refundsuccess，退款失败：refundclose
                        'alipay_trade_id' => $baseInfo['alipayTradeId'], //外部支付交易Id
                        'remark' => array_key_exists('remark', $baseInfo) == true ? $baseInfo['remark'] : '', //备注，1688指下单时的备注
                        'sum_product_payment' => $baseInfo['sumProductPayment'], //产品总金额(该订单产品明细表中的产品金额的和)，单位元
                        'buyer_feedback' => array_key_exists('buyerFeedback', $baseInfo) == true ? $baseInfo['buyerFeedback'] : '', //买家留言，不超过500字
                        'pre_order_id' => array_key_exists('preOrderId', $baseInfo) == true ? $baseInfo['preOrderId'] : '', //预订单ID
                        'buyer_login_id' => $baseInfo['buyerLoginId'], //买家loginId，旺旺Id
                        'modify_time' => array_key_exists('modifyTime', $baseInfo) == true ? date('Y-m-d H:i:s', strtotime(substr($baseInfo['modifyTime'], 0, 14))) : "0000-00-00 00:00:00", //修改时间
                        'sub_buyer_login_id' => array_key_exists('subBuyerLoginId', $baseInfo) == true ? $baseInfo['subBuyerLoginId'] : '', //买家子账号
                        'confirmed_time' => array_key_exists('confirmedTime', $baseInfo) == true ? date('Y-m-d H:i:s', strtotime(substr($baseInfo['confirmedTime'], 0, 14))) : "0000-00-00 00:00:00", //确认时间
                        'trade_type' => $baseInfo['tradeType'], //1:担保交易 2:预存款交易 3:ETC境外收单交易 4:即时到帐交易 5:保障金安全交易 6:统一交易流程 7:分阶段付款 8.货到付款交易 9.信用凭证支付交易 10.账期支付交易，50060 交易4.0
                        'receiving_time' => array_key_exists('receivingTime', $baseInfo) == true ? date('Y-m-d H:i:s', strtotime(substr($baseInfo['receivingTime'], 0, 14))) : "0000-00-00 00:00:00", //收货时间，这里返回的是完全收货时间
                        'id_of_str' => $baseInfo['idOfStr'], //交易id(字符串格式)
                        'refund_status_foras' => array_key_exists('refundStatusForAs', $baseInfo) == true ? $baseInfo['refundStatusForAs'] : '', //订单的售后退款状态
                        'complete_time' => array_key_exists('completeTime', $baseInfo) == true ? date('Y-m-d H:i:s', strtotime(substr($baseInfo['completeTime'], 0, 14))) : "0000-00-00 00:00:00", //完成时间
                        'seller_login_id' => $baseInfo['sellerLoginId'], //卖家oginId，旺旺Id
                        'seller_user_id' => $baseInfo['sellerUserId'],//卖家数字id
                        'buyer_id' => $baseInfo['buyerID'],//买家主账号id
                        'buyer_alipay_id' => $baseInfo['buyerAlipayId'],//买家支付宝id
                        'total_amount' => $baseInfo['totalAmount'],//应付款总金额，totalAmount = ∑itemAmount + shippingFee，单位为元
                        'seller_id' => $baseInfo['sellerID'],//卖家主账号id
                        'shipping_fee' => $baseInfo['shippingFee'],//运费，单位为元
                        'create_time' => array_key_exists('createTime', $baseInfo) == true ? date('Y-m-d H:i:s', strtotime(substr($baseInfo['createTime'], 0, 14))) : "0000-00-00 00:00:00",//创建时间
                        'seller_remark_icon' => array_key_exists('sellerRemarkIcon', $baseInfo) == true ? $baseInfo['sellerRemarkIcon'] : '',//卖家备忘标志
                        'seller_memo' => array_key_exists('sellerMemo', $baseInfo) == true ? $baseInfo['sellerMemo'] : '',//卖家备忘信息
                        'buyer_user_id' => $baseInfo['buyerUserId'],//买家数字id
                        'refund_id' => array_key_exists('refundId', $baseInfo) == true ? $baseInfo['refundId'] : '',//退款单ID
                        'refund' => $baseInfo['refund'],//退款金额，单位为元
                        'status' => $baseInfo['status'],//交易状态，waitbuyerpay:等待买家付款;waitsellersend:等待卖家发货;waitlogisticstakein:等待物流公司揽件;waitbuyerreceive:等待买家收货;waitbuyersign:等待买家签收;signinsuccess:买家已签收;confirm_goods:已收货;success:交易成功;cancel:交易取消;terminated:交易终止;未枚举:其他状态
                        'refund_payment' => $baseInfo['refundPayment'],//退款金额
                        'ctime' => $now_time, //创建时间
                        'mtime' => $now_time, //修改时间
                        'area' =>array_key_exists('area',$nativeLogistics)==true?$nativeLogistics['area']:'', //县，区
                        'areaCode' =>array_key_exists('areaCode',$nativeLogistics)==true?$nativeLogistics['areaCode']:'', //省市区编码
                        'city' =>array_key_exists('city',$nativeLogistics)==true?$nativeLogistics['city']:'', //城市
                        'province' =>array_key_exists('province',$nativeLogistics)==true?$nativeLogistics['province']:'', //省份
                        'zip' =>array_key_exists('zip',$nativeLogistics)==true?$nativeLogistics['zip']:'', //邮编
                        'townCode' =>array_key_exists('townCode',$nativeLogistics)==true?$nativeLogistics['townCode']:'', //镇，街道地址码
                        'town' =>array_key_exists('town',$nativeLogistics)==true?$nativeLogistics['town']:'', //镇，街道
                        'address' =>array_key_exists('address',$nativeLogistics)==true?$nativeLogistics['address']:'' //详细地址


                    );
                    $is_exit_order = self::getOrder($baseInfo['id']);
                    $order = new Order();
                    if (empty($is_exit_order)) {
                        $result = $order->insert($data_order);
                    } else {
                        $result = self::updateOrder($data_order, $baseInfo['id']);
                    }
                    if (array_key_exists('productItems', $value) == true) {
                        foreach ($value['productItems'] as $item) {
                            $data_order_sub = array(
                                'shop_id' => $shop_id, //店铺ID
                                'transaction_id' => $baseInfo['id'],  //交易id
                                'sub_item_id' => array_key_exists('subItemID', $item) == true ? $item['subItemID'] : '', //子订单号，或商品明细条目ID
                                'cargo_number' => array_key_exists('cargoNumber', $item) == true ? $item['cargoNumber'] : '', //指定单品货号，国际站无需关注。该字段不一定有值，仅仅在下单时才会把货号记录(如果卖家设置了单品货号的话)。别的订单类型的货号只能通过商品接口去获取。请注意：通过商品接口获取时的货号和下单时的货号可能不一致，因为下单完成后卖家可能修改商品信息，改变了货号。
                                'item_amount' => array_key_exists('itemAmount', $item) == true ? $item['itemAmount'] : '',  //实付金额，单位为元
                                'name' => array_key_exists('name', $item) == true ? $item['name'] : '',  //商品名称
                                'price' => array_key_exists('price', $item) == true ? $item['price'] : '',  //原始单价，以元为单位
                                'product_id' => array_key_exists('productID', $item) == true ? $item['productID'] : '',  //产品ID（非在线产品为空）
                                'product_img_url' => array_key_exists('productImgUrl', $item) == true ? json_encode($item['productImgUrl']) : '',  //商品图片url_json,["http://cbu01.alicdn.com/img/ibank/2019/700/221/12771122007.80x80.jpg"]
                                'product_snapshot_url' => array_key_exists('productSnapshotUrl', $item) == true ? $item['productSnapshotUrl'] : '',  //产品快照url，交易订单产生时会自动记录下当时的商品快照，供后续纠纷时参考
                                'quantity' => array_key_exists('quantity', $item) == true ? $item['quantity'] : '',  //以unit为单位的数量，例如多少个、多少件、多少箱、多少吨
                                'refund' => array_key_exists('refund', $item) == true ? $item['refund'] : '',  //退款金额，单位为元
                                'sku_id' => array_key_exists('skuID', $item) == true ? $item['skuID'] : '',  //skuID
                                'status' => array_key_exists('status', $item) == true ? $item['status'] : '',  //子订单状态，如果订单状态为待发货状态（waitsellersend），还需要根据canSendGoods来判断当前子订单能否发货，如果为false则当前子订单不能发货，为true则说明当前子订单可以正常发货
                                'unit' => array_key_exists('unit', $item) == true ? $item['unit'] : '',  //售卖单位 例如：个、件、箱、吨
                                'weight' => array_key_exists('weight', $item) == true ? $item['weight'] : '',  //重量 按重量单位计算的重量，例如：100
                                'weight_unit' => array_key_exists('weightUnit', $item) == true ? $item['weightUnit'] : '',  //重量单位 例如：g，kg，t
                                'sku_name' => array_key_exists('skuInfos', $item) == true ? $item['skuInfos'][0]['name'] : '',  //规格-属性名
                                'sku_value' => array_key_exists('skuInfos', $item) == true ? $item['skuInfos'][0]['value'] : '', //规格-属性值
                                'skuinfos' => array_key_exists('skuInfos', $item) == true ? json_encode($item['skuInfos']) : "",
                                'spec_id' => array_key_exists('specId', $item) == true ? $item['specId'] : '',  //订单销售属性ID
                                'refund_status' => array_key_exists('refundStatus', $item) == true ? $item['refundStatus'] : '',  //WAIT_SELLER_AGREE 等待卖家同意 REFUND_SUCCESS 退款成功 REFUND_CLOSED 退款关闭 WAIT_BUYER_MODIFY 待买家修改 WAIT_BUYER_SEND 等待买家退货 WAIT_SELLER_RECEIVE 等待卖家确认收货
                                'logistics_status' => array_key_exists('logisticsStatus', $item) == true ? $item['logisticsStatus'] : '',  //1 未发货 2 已发货 3 已收货 4 已经退货 5 部分发货 8 还未创建物流订单
                                'gmt_create' => array_key_exists('gmtCreate', $baseInfo) == true ? date('Y-m-d H:i:s', strtotime(substr($baseInfo['gmtCreate'], 0, 14))) : "0000-00-00 00:00:00",  //创建时间
                                'gmt_modified' => array_key_exists('gmtModified', $baseInfo) == true ? date('Y-m-d H:i:s', strtotime(substr($baseInfo['gmtModified'], 0, 14))) : "0000-00-00 00:00:00",  //修改时间
                                'gmt_completed' => array_key_exists('gmtCompleted', $baseInfo) == true ? date('Y-m-d H:i:s', strtotime(substr($baseInfo['gmtCompleted'], 0, 14))) : "0000-00-00 00:00:00",  //明细完成时间
                                'refund_id' => array_key_exists('refundId', $item) == true ? $item['refundId'] : '',  //退款单号
                                'can_send_goods' => array_key_exists('canSendGoods', $item) == true ? $item['canSendGoods'] : '',  //当前子订单是否可发货，如果当前子订单状态为待发货状态（waitsellersend），只要canSendGoods为false，不区分业务，该子订单则不可以发货，为true则可以正常发货
                                'cant_send_reason' => array_key_exists('cantSendReason', $item) == true ? $item['cantSendReason'] : '',  //不可发货的原因，拼团、C2M业务都有
                                'ctiem' => $now_time,  //创建时间
                                'mtime' => $now_time, //修改时间
                                'statusStr' => array_key_exists('statusStr', $item) == true ? $item['statusStr'] : '' //子订单状态描述
                            );
                            $is_exit_order_sub = self::getOrderSub(array_key_exists('subItemID', $item) == true ? $item['subItemID'] : '');
                            $order_sub = new OrderSub();
                            if (empty($is_exit_order_sub)) {
                                $result = $order_sub->insert($data_order_sub);
                            } else {
                                $result = self::updateOrderSubAll($data_order_sub, array_key_exists('subItemID', $item) == true ? $item['subItemID'] : '');
                            }
                        }
                    }
                }
            } else {
                return array_response([], 1, '获取订单信息失败');
            }
        }
        $new_arr_order = [];
        $result=self::page($data['pageNum'], $data['limit'], $where,$whereBetweentTime,$is_all);
        foreach ($result as $value){
            $resultordersub=self::order_sub($value['transaction_id']);
            $resultorderarea=self::order_area($value['transaction_id']);
            $value['province']=empty($resultorderarea[0]['province'])==true?"":$resultorderarea[0]['province'];
            $value['city']=empty($resultorderarea[0]['city'])==true?"":$resultorderarea[0]['city'];
            $value['area']=empty($resultorderarea[0]['area'])==true?"":$resultorderarea[0]['area'];
            $value['town']=empty($resultorderarea[0]['town'])==true?"":$resultorderarea[0]['town'];
            $value['address']=empty($resultorderarea[0]['address'])==true?"":$resultorderarea[0]['address'];
            $value['to_area']=empty($resultorderarea[0]['to_area'])==true?"":$resultorderarea[0]['to_area'];
            $value['province_code']="";
            $value['city_code']="";
            $value['area_code']="";
            $new_arr_order_sub = [];
            $value['quantity'] = 0;
            foreach ($resultordersub as $value1) {
                if ($value['transaction_id'] == $value1['transaction_id']) {
                    $new_arr_order_sub[] = array(
                        'os_id' => $value1['os_id'],
                        'price' => $value1['price'],
                        'quantity' => $value1['quantity'],
                        'item_amount' => $value1['item_amount'],
                        'name' => $value1['name'],
                        'product_img_url'=>empty(json_decode($value1['product_img_url'],true))==true ?array() :json_decode($value1['product_img_url'],true),
                        'baby_short_name'=>empty($value1['baby_short_name'])==true?"":$value1['baby_short_name'],
                        'sku_short_name'=>empty($value1['sku_short_name'])==true?"":$value1['sku_short_name'],
                        'skuinfos'=>empty(json_decode($value1['skuinfos'],true))==true ?array() :json_decode($value1['skuinfos'],true),
                        'statusStr'=>$value1['statusStr']
                    );
                    $value['order_sub'] = $new_arr_order_sub;
                    $value['quantity']=$value['quantity']+$value1['quantity'];
                }
            }
        }
        $buyer_count = self::buyer_count($where,$whereBetweentTime,$is_all);
        $arr=json_decode(json_encode($result),true);
        $arr['buyer_count'] = $buyer_count;
        return $arr;
    }
    /**
     * @todo 查询主订单是否存在
     * @author yangfan
     */
    public static function getOrder($transaction_id){
        $order = new Order();
        $result = $order->field('transaction_id')
            ->where('transaction_id',$transaction_id)
            ->find();
        return $result;
    }
    /**
     * @todo 更新主订单表信息
     * @author yangfan
     */
    public static function updateOrder($data,$transaction_id){
        $result = Db::name('order')
            ->where('transaction_id', $transaction_id)
            ->data($data)
            ->update();
        return $result;
    }
    /**
     * @todo 更新子订单表信息
     * @author yangfan
     */
    public static function updateOrderSubAll($data,$sub_item_id){
        $result = Db::name('order_sub')
            ->where('sub_item_id', $sub_item_id)
            ->data($data)
            ->update();
        return $result;
    }
    /**
     * @todo 查询子订单是否存在
     * @author yangfan
     */
    public static function getOrderSub($sub_item_id){
        $order_sub = new OrderSub();
        $result = $order_sub->field('sub_item_id')
            ->where('sub_item_id',$sub_item_id)
            ->find();
        return $result;
    }
    /**
     * @todo 修改订单收货地址
     * @author yangfan
     */
    public static function UpdateOrderArea($transaction_id,$to_area,$data){
        $result=Db::name('order')
        ->where('transaction_id', $transaction_id)
        ->update(['to_area' => $to_area,'u_area'=>$data['area'],
                   'u_city'=>$data['city'],'u_province'=>$data['province'],
                   'u_town'=>$data['town'],'u_address'=>$data['address']]);
       // $order = new Order();
        //$result = $order::update(['to_area' => $to_area],['transaction_id' => $transaction_id]);
        return $result;
    }
    /**
     * @todo 单个打印：更新快递单打印状态
     * @author hubiao
     */
    public static function updateExpressState($id = 0){
        //判断id有效性
        $order = Order::find($id);
        if (empty($order)){
            $result["code"] = 1;
            $result["msg"] = "主键ID不存在";
            return $result;
        }
        $order->express_print_state = 1;
        if ($order->save()){
            $result["code"] = 0;
            $result["msg"] = "更新成功";
        }else{
            $result["code"] = 1;
            $result["msg"] = "更新失败";
        }
        return $result;
    }
    /**
     * @todo 单个打印：更新发货单打印状态
     * @author hubiao
     */
    public static function updateInvoiceState($id = 0){
        //判断id有效性
        $order = Order::find($id);
        if (empty($order)){
            $result["code"] = 1;
            $result["msg"] = "主键ID不存在";
            return $result;
        }
        $order->invoice_print_state = 1;
        if ($order->save()){
            $result["code"] = 0;
            $result["msg"] = "更新成功";
        }else{
            $result["code"] = 1;
            $result["msg"] = "更新失败";
        }
        return $result;
    }
    /**
     * @todo 物流发货-无需物流
     * @author hubiao
     */
    public static function opDeliverySendOrderDummy($shop_id = 0,$param = []){
        $ali_util = new AlibabaUtil();
        return $ali_util->opDeliverySendOrderDummy($shop_id,$param);
    }

    /**
     * @todo 物流发货-自己联系物流发货
     * @author hubiao
     */
    public static function opDeliverySendOrderOffline($shop_id = 0,$param = []){
        $ali_util = new AlibabaUtil();
        return $ali_util->opDeliverySendOrderOffline($shop_id,$param);
    }
    /**
     * @todo 批量打印：修改备注
     * @author hubiao
     */
    public static function orderMemoAdd($shop_id = 0,$param = []){
        $ali_util = new AlibabaUtil();
        return $ali_util->orderMemoAdd($shop_id, $param);
    }

    /**
     * @todo 批量打印：订单详情
     * @author hubiao
     */
    public static function getSellerView($shop_id = 0,$param = []){
        $ali_util = new AlibabaUtil();
        return $ali_util->getSellerView($shop_id, $param);
    }
}